<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use addons\kefu\library\Common;
use addons\kefu\library\Captcha;

/**
 * 发私信
 *
 * @icon fa fa-circle-o
 */
class Usermsg extends Backend
{

    /**
     * Usermsg模型对象
     * @var \app\admin\model\Usermsg
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Usermsg;
        $this->view->assign("stateList", $this->model->getStateList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','content','createtime','state']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['nickname','email']);
                $kefuid = Db::name('kefu_user')->where(['user_id'=>$row['user_id']])->value('id');
                $sessionid = Db::name('kefu_session')->where(['user_id'=>$kefuid,'deletetime'=>null])->value('id');
                $status = Db::name('kefu_record')->where(['session_id'=>$sessionid,'sender_identity'=>0,'message'=>$row['content']])->order('createtime desc')->value('status');
                if ($row['state']!==$status) {
                    Db::name('user_msg')->where('id',$row['id'])->update(['state'=>$status]);
                    $row['state'] = $status;
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $this->usersendkefu($params['user_id'],$params['content']);
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $userid = Db::name('user_msg')->where('id',$params['id'])->value('user_id');
            $kefuid = Db::name('kefu_user')->where(['user_id'=>$userid])->value('id');
            $sessionid = Db::name('kefu_session')->where(['user_id'=>$kefuid,'deletetime'=>null])->value('id');
            $recid = Db::name('kefu_record')->where(['session_id'=>$sessionid,'sender_identity'=>0])->order('createtime desc')->value('id');
            Db::name('kefu_record')->where(['id'=>$recid])->update(['message'=>$params['content'],'status'=>0]);

            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 真实删除
     *
     * @param $ids
     * @return void
     */
    public function destroy($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
                $kefuid = Db::name('kefu_user')->where(['user_id'=>$item['user_id']])->value('id');
                $sessionid = Db::name('kefu_session')->where(['user_id'=>$kefuid,'deletetime'=>null])->value('id');
                //Db::name('kefu_record')->where(['session_id'=>$sessionid,'sender_identity'=>0,'message'=>$item['content']])->delete();
                $count += $item->delete(true);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    //客服给用户发送消息 用户id，消息内容
    function usersendkefu($userid,$str){
        $user = Db::name('user')->where(['id'=>$userid])->field('nickname,avatar')->find();
        //创建用户
        $kefuid = Db::name('kefu_user')->where(['user_id'=>$userid])->value('id');
        if (!$kefuid) {
            $token = \fast\Random::uuid();
            $kefuid = Db::name('kefu_user')->insertGetId(['user_id'=>$userid,'avatar'=>$user['avatar'],'nickname'=>$user['nickname'],'token'=>$token,'createtime'=>time()]);
        }
        //创建会话
        $session = Db::name('kefu_session')->where(['user_id'=>$kefuid,'deletetime'=>null])->find();
        if (!$session) {
            // 客服分配
            // $csr = Common::getAppropriateCsr();
            // if ($csr) {
            //     $session = Common::distributionCsr($csr, $userid . '||user');
            // } else {
            //     //无法分配到客服发给admin
               
            // }
            $session = Common::distributionCsr('1||csr', $kefuid . '||user');
            
        }
        $note = '给用户 ' . $user['nickname'] . ' 发私信 ';
        // 记录轨迹
        $trajectory = [
            'user_id'    => $kefuid,
            'csr_id'     => $session['csr_id'],
            'log_type'   => 0,
            'note'       => $note,
            'url'        => '',
            'referrer'   => '',
            'createtime' => time(),
        ];
        Db::name('kefu_trajectory')->insert($trajectory);
        // 插入接待记录,用于数据统计
        $reception_log = [
            'csr_id'     => $session['csr_id'],
            'user_id'    => $kefuid,
            'createtime' => time(),
        ];
        Db::name('kefu_reception_log')->insert($reception_log);
        //客服给用户发消息 0=富文本消息 3=系统消息
         $aa = Common::chatRecord($session['id'],$str, 0,'1||csr');
         return true;
    }

}
